package com.cloudsigns.factorymanager2.engineering.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;

import com.cloudsigns.factorymanager2.project.utils.ConstantUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by tony on 2018/4/13.
 */

public class PhotoUtil {
    public static final String ROOT = Environment.getExternalStorageDirectory() + File.separator;
    public static final String CAMERA_CACHE = ROOT + "guanli/myimages/";
    public static final String CAMERA_SEVER = ROOT + "guanli/serveriamges/";
    public static final String IMAGE_UNSPECIFIED = "image/*";//随意图片类型
    public static final int CAMERA = 1;// 拍照
    public static final int GALLERY = 2; // 相册
    public static final int PHOTORESOULT = 3;// 结果
    public static final int PICTURE_HEIGHT = 500;
    public static final int PICTURE_WIDTH = 500;
    public static String filePath = "";


    public static void makeFileDir() {
        mkdirectory(CAMERA_CACHE);
        mkdirectory(CAMERA_SEVER);
    }

    private static void mkdirectory(String file) {
        File f = new File(file);
        if (!f.exists()) {
            f.mkdirs();
        }
    }

    public static void startGallery(Activity activity, Fragment fragment) {
        makeFileDir();
        createLocalFile();
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                "image/*");

        if (null != activity)
            activity.startActivityForResult(intent, GALLERY);
        else if (null != fragment)
            fragment.startActivityForResult(intent, GALLERY);


    }


    public static void startCamear(Activity activity, Fragment fragment) {
        makeFileDir();
        /*android6.0以上 需要在代码中注册调用相机权限*/
        if(null != activity){
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    1);
        }else{
            if(null != fragment){
                ActivityCompat.requestPermissions(fragment.getActivity(),
                        new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        1);
            }
        }

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File fCurrentFile = createLocalFile();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(fCurrentFile));
        if (null != activity)
            activity.startActivityForResult(intent, CAMERA);
        else if (null != fragment)
            fragment.startActivityForResult(intent, CAMERA);
    }

    /**
     * 获取当前系统时间并格式化
     *
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static String getStringToday() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    public static File createLocalFile() {

        filePath = CAMERA_CACHE + getStringToday() + ".jpg";
        File fCurrentFile = new File(filePath);
        return fCurrentFile;
    }

    public static File createDestFile(String destPath) {
        File fCurrentFile = new File(destPath);
        return fCurrentFile;
    }

    /**
     * 图片裁剪
     *
     * @param activity
     * @param uri
     * @param height
     * @param width
     */
    public static void startPhotoZoom(Activity activity, Uri uri, int height, int width) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", height);
        intent.putExtra("outputY", width);
        intent.putExtra("noFaceDetection", true); //关闭人脸检測
        intent.putExtra("return-data", true);//假设设为true则返回bitmap
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//输出文件
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        activity.startActivityForResult(intent, PHOTORESOULT);
    }

    public static String imageCompressionAndSave(String oldFileName, String newFileName) {
        String notExists = "";
        FileOutputStream fOut = null;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 1;
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(oldFileName, options);

            // 480 * 800
            options.inSampleSize = computeSampleSize(options, 480, 800);

            options.inJustDecodeBounds = false;
            options.inDither = false;
            options.inPurgeable = true;
            options.inInputShareable = true;
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            Bitmap sourceBitmap = BitmapFactory.decodeFile(oldFileName, options);
            if (null != sourceBitmap) {
                /** 旋转图片 */
                int degree = readBitmapDegree(oldFileName);
                if (0 != degree) {
                    Matrix matrix = new Matrix();
                    matrix.setRotate(degree);
                    Bitmap newbmp = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), matrix, true);
                    if (null != newbmp) {
                        BufferedOutputStream bos;
                        if (sourceBitmap != null && !sourceBitmap.isRecycled()) {
                            sourceBitmap.recycle();
                            sourceBitmap = null;
                        }
                        bos = new BufferedOutputStream(new FileOutputStream(oldFileName));
                        newbmp.compress(Bitmap.CompressFormat.JPEG, 60, bos);
                        bos.flush();
                        bos.close();
                        sourceBitmap = newbmp;
                    }
                }
            }
            File newFile = new File(newFileName);
            if (!newFile.exists())
                createDestFile(newFileName);

            if (null != sourceBitmap) {
                fOut = new FileOutputStream(newFile);
                sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 60, fOut);
                fOut.flush();
                sourceBitmap.recycle();
            } else {
                return notExists;
            }
        } catch (Exception e) {
            e.printStackTrace();
            newFileName = null;

            return notExists;
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            newFileName = null;

        } finally {
            if (null != fOut) {
                try {
                    fOut.close();
                } catch (IOException e) {
                    e.printStackTrace();

                    return notExists;
                }
            }
        }
        return newFileName;
    }


    private static int computeSampleSize(BitmapFactory.Options options, int targeW, int targeH) {
        int w = options.outWidth;
        int h = options.outHeight;
        float candidateW = w / targeW;
        float candidateH = h / targeH;

        float candidate = Math.max(candidateW, candidateH);
        if (candidate == 0) {
            return 1;
        }
        if (candidate > 1) {
            if ((w > targeW) && (w / candidate) < targeW) {
                candidate -= 1;
            }
        }

        if (candidate > 1) {
            if ((h > targeH) && (h / candidate) < targeH) {
                candidate -= 1;
            }
        }

        return (int) candidate;
    }


    public static int readBitmapDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

}
